//
//  KSScanViewController.swift
//  Supermarket
//
//  Created by Black_Crystal on 2017/9/27.
//  Copyright © 2017年 kushao. All rights reserved.
//

import UIKit
import AVFoundation

class KSScanViewController: KSBaseViewController,AVCaptureMetadataOutputObjectsDelegate {
    
    var videoPreviewLayer =  AVCaptureVideoPreviewLayer()
    private var lineImg = UIImageView()
    private var tableview: UITableView!
    private let typeLabel = UILabel()
    private let scanRect = CGRect.init(x: (KSConstants.kScreenWidth - KSConstants.kScreenWidth * 2/3)/2, y: (KSConstants.kScreenHeight - 89 - 64 - KSConstants.kScreenWidth * 2/3)/2, width: KSConstants.kScreenWidth * 2/3, height: KSConstants.kScreenWidth * 2/3)
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        
        let rightFlashlightBtn = UIButton()
        rightFlashlightBtn.setBackgroundImage(UIImage.init(named: "Home_Flashlight_on"), for: .normal)
        rightFlashlightBtn.setBackgroundImage(UIImage.init(named: "Home_Flashlight_open"), for: .selected)
        rightFlashlightBtn.addTarget(self, action: #selector(flashLightEvent(button:)), for: .touchDown)
        let rightBar = UIBarButtonItem.init(customView: rightFlashlightBtn)
        self.navigationItem.rightBarButtonItem = rightBar
        
        typeLabel.frame = CGRect.init(x: 10, y: scanRect.maxY + 10, width: 100, height: 40)
        typeLabel.text = "分拣商品:"
        typeLabel.textColor = UIColor.white
        self.view.addSubview(typeLabel)
        
        tableview = UITableView()
        tableview.register(KSScanTableViewCell.self, forCellReuseIdentifier: "KSScanTableViewCell")
        tableview.showsVerticalScrollIndicator = false
        tableview.backgroundColor = UIColor.clear
        tableview.separatorStyle = .none
        tableview.delegate = self
        tableview.dataSource = self
        self.view.addSubview(tableview)
        tableview.snp.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.top.equalTo(typeLabel.snp.bottom).offset(10)
            make.bottom.equalTo(-10)
        }
        
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        self.configUI()
    }
    
    private func configUI() {
        
        let captureDevice = AVCaptureDevice.default(for: .video)
        var input: AVCaptureDeviceInput
        let captureSession = AVCaptureSession()
        do {
            input = try AVCaptureDeviceInput.init(device: captureDevice!)
            captureSession.addInput(input)
        } catch {
           self.navigationController?.popViewController(animated: true)
        }
        
        let captureMetadataOutput = AVCaptureMetadataOutput()
        captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.init(label: "ease_capture_queue"))
        captureSession.addOutput(captureMetadataOutput)
        
        if !captureMetadataOutput.availableMetadataObjectTypes.contains(AVMetadataObject.ObjectType.qr) {
            let alertViewController = UIAlertController.init(title: nil, message: "摄像头不支持扫描二维码", preferredStyle: .actionSheet)
            self.present(alertViewController, animated: true) {}
            self.navigationController?.popViewController(animated: true)
        } else {
            captureMetadataOutput.metadataObjectTypes = captureMetadataOutput.availableMetadataObjectTypes
        }
        captureMetadataOutput.rectOfInterest = CGRect.init(x: scanRect.minY/self.view.frame.height, y: 1 - scanRect.maxX/self.view.frame.width, width: scanRect.height/self.view.frame.height, height: scanRect.width/self.view.frame.width)
        videoPreviewLayer = AVCaptureVideoPreviewLayer.init(session: captureSession)
        videoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        videoPreviewLayer.frame = self.view.bounds
        
        self.view.layer.addSublayer(videoPreviewLayer)
        videoPreviewLayer.session?.startRunning()
        
        let backView = UIView.init(frame: self.view.bounds)
        backView.backgroundColor = UIColor.black.withAlphaComponent(0.8)
        self.view.addSubview(backView)
        
        let hintView = UIView()
        hintView.backgroundColor = KSColor.kColor_3
        hintView.layer.cornerRadius = 17
        backView.addSubview(hintView)
        hintView.snp.makeConstraints { (make) in
            make.centerX.equalTo(backView)
            make.top.equalTo(60)
            make.width.equalTo(180)
            make.height.equalTo(30)
        }
        
        let leftImg = UIImageView()
        leftImg.image = UIImage.init(named: "Home_Left")
        hintView.addSubview(leftImg)
        leftImg.snp.makeConstraints { (make) in
            make.top.equalTo(5)
            make.bottom.equalTo(-5)
            make.left.equalTo(0)
            make.width.equalTo(10)
        }
        
        let rightImg = UIImageView()
        rightImg.image = UIImage.init(named: "Home_Right")
        hintView.addSubview(rightImg)
        rightImg.snp.makeConstraints { (make) in
            make.top.equalTo(5)
            make.bottom.equalTo(-5)
            make.right.equalTo(0)
            make.width.equalTo(10)
        }
        
        let hintLabel = UILabel()
        hintLabel.text = "将条形码放入框内"
        hintLabel.textColor = UIColor.white
        hintLabel.font = UIFont.systemFont(ofSize: 14)
        hintView.addSubview(hintLabel)
        hintLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(hintView)
            make.centerY.equalTo(hintView)
        }
        
        let shapLater = CAShapeLayer()
        let path = UIBezierPath.init(rect: self.view.bounds)
        let rectanglePath = UIBezierPath.init(rect: scanRect).reversing()
        path.append(rectanglePath)
        shapLater.path = path.cgPath
        backView.layer.mask = shapLater
        
        let borderImg = UIImageView.init(frame: scanRect)
        borderImg.image = UIImage.init(named: "Home_border")
        self.view.addSubview(borderImg)
        
        lineImg.frame = CGRect.init(x: scanRect.origin.x, y: scanRect.origin.y, width: scanRect.width, height: 2)
        lineImg.image = UIImage.init(named: "Home_Line")
        self.view.addSubview(lineImg)
        
        self.view.bringSubview(toFront: typeLabel)
        self.view.bringSubview(toFront: tableview)
        
        self.scanLineStartAction()
    }
    
    private func startScan() {
        videoPreviewLayer.session?.stopRunning()
        self.scanLineStartAction()
    }
    
    private func stopScan() {
        videoPreviewLayer.session?.stopRunning()
        self.scanLineStopAction()
    }
    
    private func scanLineStartAction() {
        let scanAnimation = CABasicAnimation.init(keyPath: "position.y")
        scanAnimation.fromValue = lineImg.frame.origin.y
        scanAnimation.toValue = lineImg.frame.origin.y + KSConstants.kScreenWidth * 2/3
        scanAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)
        scanAnimation.repeatCount = 10000
        scanAnimation.duration = 2.0
        self.lineImg.layer.add(scanAnimation, forKey: "basic")
        
    }
    
    private func scanLineStopAction() {
        lineImg.layer.removeAllAnimations()
    }
    
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        for object in metadataObjects {
            if (object.isKind(of: AVMetadataMachineReadableCodeObject.self)) && (object.type == AVMetadataObject.ObjectType.qr) {
                let resultConten = (object as! AVMetadataMachineReadableCodeObject).stringValue
                self.stopScan()
            }
        }
    }
    
    @objc func flashLightEvent(button: UIButton) {
            let device = AVCaptureDevice.default(for: .video)
            if device == nil {
                return
            }
            if device?.torchMode == AVCaptureDevice.TorchMode.off{
                do {
                    try device?.lockForConfiguration()
                } catch {
                    return
                }
                device?.torchMode = .on
                device?.unlockForConfiguration()
                button.isSelected = true
            }else {
                do {
                    try device?.lockForConfiguration()
                } catch {
                    return
                }
                device?.torchMode = .off
                device?.unlockForConfiguration()
                button.isSelected = false
            }
    }
    
    deinit {
        videoPreviewLayer.removeFromSuperlayer()
        self.scanLineStopAction()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension KSScanViewController: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return KSTools.getHeightByWidth(KSConstants.kScreenWidth - 90, title: "汪汪汪汪汪无无无无无无无无无无无无无无无无无无无无无无无无无无无无无无无无无无", size: 15) + 10
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "KSScanTableViewCell", for: indexPath)
        return cell
    }
}

